package com.marry.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.marry.config.SslUtils;
import com.marry.model.LoginRequest;
import com.marry.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录
 */
@RestController
@RequestMapping("/sys")
public class LoginController {

    @Autowired
    private WxMaService wxService;

    /**
     * 登录验证
     * @return
     */
    @RequestMapping("/login")
    public Result login(LoginRequest request) throws Exception {
        WxMaJscode2SessionResult session =
                wxService.getUserService().getSessionInfo(request.getCode());
        if (null == session) {
            throw new RuntimeException("login handler error");
        }
        return Result.ok(session);
    }
    /**
     * 获取用户
     * @return
     */
    @RequestMapping("/getUser")
    public Result getUser(LoginRequest request) throws Exception {
        WxMaJscode2SessionResult session =
                wxService.getUserService().getSessionInfo(request.getCode());
        if (null == session) {
            return Result.error("login handler error");
        }
        // 解密用户信息
        WxMaUserInfo wxUserInfo = wxService.getUserService().getUserInfo(session.getSessionKey(),
                request.getEncryptedData(), request.getIv());
        if (null == wxUserInfo) {
            return Result.error("wxUser not exist");
        }
        return Result.ok(wxUserInfo);
    }

}
